<template>
  <div class="wrapper">
    <!-- 活动列表 -->
    <el-card class="form-wrapper" shadow="never">
      <el-form class="form" :model="formData" inline>
        <el-form-item label="商家" prop="merchantId">
          <el-select v-model="formData.merchantId" filterable remote reserve-keyword placeholder="输入搜索"
            :remote-method="searchMerchants" :loading="loading" style="width: 240px">
            <el-option v-for="item in merchants" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="业务员" props="salesmanId">
          <el-input v-model="formData.salesmanId" clearable @keyup.enter="resetPage" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-input v-model="formData.status" clearable @keyup.enter="resetPage" />
        </el-form-item>

        <!-- <el-form-item label="抽奖时间">
          <el-input v-model="formData.nickname" clearable @keyup.enter="resetPage" />
        </el-form-item> -->

        <el-form-item>
          <el-button type="primary" @click="resetPage">查询</el-button>
          <el-button @click="resetParams">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="pager.loading" class="mt-4 !border-none" shadow="never">

      <el-button type="primary" size="small" plain @click="handleAdd">
        <template #icon>
          <icon name="el-icon-Plus" />
        </template>
        新增
      </el-button>
      <div class="mt-4">
        <el-table :data="pager.lists" size="large">

          <el-table-column label="序号" prop="id" min-width="60" />
          <el-table-column label="活动名称" prop="title" min-width="60" />
          <el-table-column label="商家" prop="merchantName" min-width="60" />
          <el-table-column label="活动类型" min-width="120">
            <template #default="{ row }">
              <span>{{ row.typeText }}</span>
              <el-tag class="cursor-pointer" type="default" @click="handleOpenQrcodeInfoPopup(row)">查看</el-tag>
              <!-- <span v-if="row.type === 1">
                刮刮卡 <el-tag class="cursor-pointer" type="default" @click="handleOpenGuagualePopup(row)">查看</el-tag>
              </span>
              <span v-else>
                二维码
                <el-tag class="cursor-pointer" type="default" @click="handleOpenQrcodePopup(row)">查看</el-tag>
              </span> -->
            </template>
          </el-table-column>
          <el-table-column label="活动名额" prop="num" min-width="60" />
          <el-table-column label="剩余名额" prop="residueCount" min-width="60" />
          <el-table-column label="开始时间" prop="startTime" min-width="60" />
          <el-table-column label="结束时间" prop="endTime" min-width="60" />
          <el-table-column label="状态" prop="status">
            <template #default="{ row }">
              <el-switch :disabled="row.lock === 1" v-model="row.status" style="
                  --el-switch-on-color: #13ce66;
                  --el-switch-off-color: #a8abb2;
                " active-text="上线" inactive-text="下架" :active-value="1" :inactive-value="0"
                @change="changeStatus(row.status, row.id)" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-dropdown>
                <el-button link type="primary">操作</el-button>
                <template #dropdown v-if="row.lock !== 1">
                  <el-dropdown-item type="primary" link @click="handleEdit(row)">
                    编辑
                  </el-dropdown-item>
                  <el-dropdown-item type="primary" link @click="handleCancleActiviy(row.id)">
                    作废活动
                  </el-dropdown-item>
                  <!-- <el-dropdown-item v-if="row.id != 1" type="danger" link @click="handleDelete(row.id)">
                  删除
                </el-dropdown-item> -->
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="flex mt-4 justify-end">
        <pagination v-model="pager" @change="getLists" />
      </div>
    </el-card>
  </div>
  <edit-popup v-if="showEdit" ref="editRef" @success="getLists" @close="showEdit = false" />
  <qrcode-info-vue v-if="showQrcodeInfo" ref="qrcodeInfoRef" @close="showQrcodeInfo = false" />
</template>

<script lang="ts" setup>
import {
  deleteApi,
  listsApi as loadActivityListsApi,
  statusApi,
  invalidateActivityApi
} from '@/api/activity/activity'
import { listsApi as getMerchantListsApi } from '@/api/merchant'
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback'
import EditPopup from './edit.vue'
import { onMounted, reactive, ref, shallowRef } from 'vue'
import pagination from '@/components/pagination/index.vue'
import QrcodeInfoVue from './qrcodeInfo.vue'
import { codesStatisticsApi } from '@/api/activity/code'
const router = useRouter()
const editRef = shallowRef<InstanceType<typeof EditPopup>>()
const showEdit = ref(false)
const qrcodeInfoRef = shallowRef<InstanceType<typeof QrcodeInfoVue>>()
const showQrcodeInfo = ref(false)
// 表单数据
const formData = reactive({
  merchantId: '',
  salesmanId: '',
  merchantName: '',
  status: '',
})
const { pager, getLists, resetParams, resetPage } = usePaging({
  fetchFun: loadActivityListsApi,
  params: formData,
})

const changeStatus = async (status: any, id: number) => {
  try {
    await feedback.confirm(`确定${status ? '上线' : '下架'}当前活动？`)
    await statusApi({ id, status })
    feedback.msgSuccess('修改成功')
    getLists()
  } catch (error) {
    getLists()
  }
}

const handleAdd = async () => {
  router.push(
    {
      path: '/lucky/activityDetail',
      query: {
        type: "add"
      }
    }
  )
}

const handleEdit = async (data: any) => {
  router.push(
    {
      path: '/lucky/activityDetail',
      query: {
        type: "edit",
        id: data.id
      }
    }
  )
}

async function handleOpenQrcodeInfoPopup(row: any) {
  showQrcodeInfo.value = true
  await nextTick()
  qrcodeInfoRef.value?.open()
  qrcodeInfoRef.value?.setQrcodeInfo(row)

}
const handleDelete = async (id: number) => {
  await feedback.confirm('确定要删除？')
  await deleteApi({ id })
  feedback.msgSuccess('删除成功')
  getLists()
}
const handleCancleActiviy = async (id: number) => {
  const data = await loadCodeStatistics(id)
  await feedback.confirm(`将释放${data.statistics.bound}个未使用的刮刮卡,此活动以后不能在进行编辑，并做下架处理。客户也不能再抽奖。确定要作废吗？`)
  await invalidateActivityApi({ activityId: id })
  feedback.msgSuccess('释放成功')
  getLists()
}
const loadCodeStatistics = async (activityId: number) => {
  const data = await codesStatisticsApi({
    activityId,
  })
  return data
}
const merchants = ref<Array<any>>([])
const loading = ref(false)
const searchMerchants = (name: string) => {
  loading.value = true
  merchants.value = []
  getMerchantListsApi({
    name,
    pageSize: 10,
  })
    .then(data => {
      merchants.value = data.lists
      loading.value = false
    })
    .catch(() => {
      loading.value = false
      merchants.value = []
    })
}
onMounted(() => {
  getLists()
})
</script>
<style lang="scss" scoped>
.text_hidden {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
}

.wrapper {
  .form-wrapper {
    padding-bottom: 0px;

    .form {
      // margin-bottom: 14px;
    }
  }
}
</style>
